package com.swt.draw.controller;

import com.alibaba.fastjson.JSONObject;
import com.swt.draw.dao.AdminMapper;
import com.swt.draw.dao.AdminPostMapper;
import com.swt.draw.dao.AdminRoleMapper;
import com.swt.draw.dao.PostMapper;
import com.swt.draw.entity.*;
import com.swt.draw.example.AdminExample;
import com.swt.draw.example.AdminPostExample;
import com.swt.draw.example.AdminRoleExample;
import com.swt.draw.vo.AdminDetailVO;
import com.swt.draw.vo.BaseResponse;
import com.swt.draw.vo.LayTableResponseVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName
 * @Description TODO
 * @Author Administrator
 * @Date 2019/8/23 0023 22:07
 * @Version 1.0
 **/
@RestController
@RequestMapping("/api")
public class AdminController {

    @Resource
    private AdminMapper adminMapper;
    @Resource
    private AdminPostMapper adminPostMapper;
    @Resource
    private AdminRoleMapper adminRoleMapper;

    /**
     * @return com.swt.draw.vo.LayTableResponseVO<com.swt.draw.vo.AdminDetailVO>
     * @Author ZPF
     * @Description 根据部门获取用户
     * @Date 23:57 2019/8/25 0025
     * @Param [page, limit, departmentNos]
     **/
    @GetMapping("/getAdminList")
    public LayTableResponseVO<AdminDetailVO> getAdminList(Integer page, Integer limit, String departmentNos, Admin admin) {
        String[] depNos = {};
        if (StringUtils.isNotEmpty(departmentNos)) {
            depNos = departmentNos.split(",");
        }
        LayTableResponseVO<AdminDetailVO> adminData = new LayTableResponseVO();
        Long count = adminMapper.selectAdminCount(depNos, admin);
        List<AdminDetailVO> admins = adminMapper.selectAdminWithDep((page - 1) * limit, page * limit, depNos, admin);
        adminData.setCode(200);
        adminData.setMsg("success");
        adminData.setCount(count);
        adminData.setData(admins);
        return adminData;
    }

    /**
     * @return com.swt.draw.vo.BaseResponse
     * @Author ZPF
     * @Description 添加用户
     * @Date 23:59 2019/8/25 0025
     * @Param [admin]
     **/
    @PostMapping("/addAdmin")
    @Transactional
    public BaseResponse addAdmin(Admin admin, String[] postNo, String[] roleNo) {
        BaseResponse response = new BaseResponse();
        if(postNo == null || roleNo == null || admin == null){
            return response;
        }
        admin.setAdminCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        admin.setAdminCreateBy(((Admin) SecurityUtils.getSubject().getPrincipal()).getAdminNo());
        String adminNo = "admin-" + UUID.randomUUID().toString();
        admin.setAdminNo(adminNo);
        admin.setAdminPwd(new Md5Hash(admin.getAdminPwd(), admin.getAdminLoginName(), 2).toString());
        admin.setAdminStatus((short) 0);
        if(StringUtils.isEmpty(admin.getAdminSex())){
            admin.setAdminSex("unknow");
        }
        adminMapper.insertSelective(admin);
        AdminRole adminRole = new AdminRole();
        adminRole.setAdminRoleAdminNo(adminNo);
        for (String no : roleNo) {
            adminRole.setAdminRoleRoleNo(no);
            adminRoleMapper.insertSelective(adminRole);
        }
        AdminPost adminPost = new AdminPost();
        adminPost.setAdminPostAdminNo(adminNo);
        for (String no : postNo) {
            adminPost.setAdminPostPostNo(no);
            adminPostMapper.insertSelective(adminPost);
        }
        response.setCode(1001);
        response.setDesc("success");
        return response;
    }

    @PostMapping("/delAdmin")
    @Transactional
    public BaseResponse delAdmin(@RequestParam(value = "adminNos[]") String[] adminNos) throws Exception {
        BaseResponse response = new BaseResponse();
        AdminExample example = new AdminExample();
        AdminExample.Criteria criteria = example.createCriteria();
        criteria.andAdminNoIn(Arrays.asList(adminNos));
        Admin admin = new Admin();
        admin.setAdminStatus((short) 2);
        Integer rows = adminMapper.updateByExampleSelective(admin, example);
        if(rows == adminNos.length){
            response.setCode(1001);
            response.setDesc("删除成功");
        }else {
            throw new Exception();
        }
        return response;
    }

    @PostMapping("/updateAdmin")
    @Transactional
    public BaseResponse updateAdmin(Admin admin, String[] postNo, String[] roleNo){
        BaseResponse response = new BaseResponse();
        // 修改基本信息
        AdminExample example = new AdminExample();
        AdminExample.Criteria criteria = example.createCriteria();
        criteria.andAdminNoEqualTo(admin.getAdminNo());
        adminMapper.updateByExampleSelective(admin, example);
        // 修改角色信息
        AdminRoleExample adminRoleExample = new AdminRoleExample();
        AdminRoleExample.Criteria adminRoleCriteria = adminRoleExample.createCriteria();
        adminRoleCriteria.andAdminRoleAdminNoEqualTo(admin.getAdminNo());
        adminRoleMapper.deleteByExample(adminRoleExample);
        if(roleNo != null){
            // 重新建立角色关系
            for(String role : roleNo){
                AdminRole adminRole = new AdminRole(admin.getAdminNo(), role);
                adminRoleMapper.insertSelective(adminRole);
            }
        }
        // 修改岗位信息
        AdminPostExample adminPostExample =  new AdminPostExample();
        AdminPostExample.Criteria adminPostCriteria = adminPostExample.createCriteria();
        adminPostCriteria.andAdminPostAdminNoEqualTo(admin.getAdminNo());
        adminPostMapper.deleteByExample(adminPostExample);
        if(postNo != null){
            // 重新建立岗位关系
            for(String post: postNo){
                AdminPost adminPost = new AdminPost();
                adminPostMapper.insertSelective(adminPost);
            }
        }
        response.setCode(1001);
        response.setDesc("success");
        return response;
    }

    /**
     * @Author ZPF
     * @Description 修改用户基本信息
     * @Date 15:13 2019/9/1 0001
     * @Param [admin]
     * @return com.swt.draw.vo.BaseResponse
     **/
    @PostMapping("/updateAdminBaseInfo")
    public BaseResponse updateAdminBaseInfo(@RequestBody Admin admin){
        BaseResponse response = new BaseResponse();
        if(StringUtils.isNotEmpty(admin.getAdminPwd())){
            admin.setAdminPwd(new Md5Hash(admin.getAdminPwd(), admin.getAdminLoginName(), 2).toString());
        }
        AdminExample example = new AdminExample();
        AdminExample.Criteria criteria = example.createCriteria();
        criteria.andAdminNoEqualTo(admin.getAdminNo());
        adminMapper.updateByExampleSelective(admin, example);
        response.setCode(1001);
        response.setDesc("success");
        return response;
    }

    /**
     * @Author ZPF
     * @Description 检查登录账号是否已存在
     * @Date 1:00 2019/8/26 0026
     * @Param [loginName]
     * @return com.swt.draw.vo.BaseResponse
     **/
    @PostMapping("/validLoginName")
    public BaseResponse validLoginName(String loginName, String adminNo){
        BaseResponse response = new BaseResponse();
        AdminExample example = new AdminExample();
        AdminExample.Criteria criteria = example.createCriteria();
        criteria.andAdminLoginNameEqualTo(loginName);
        List<Admin> admins = adminMapper.selectByExample(example);
        if(admins != null && admins.size() > 0){
            for(Admin admin: admins){
                if(!admin.getAdminNo().equals(adminNo)){
                    response.setCode(1002);
                    response.setDesc("此登录账户名已存在,请更改");
                    return response;
                }
            }
            response.setCode(1001);
            response.setDesc("此登录账号可用");
        }else {
            response.setCode(1001);
            response.setDesc("此登录账号可用");
        }
        return response;
    }

    /**
     * @Author ZPF
     * @Description 管理员修改账户密码
     * @Date 11:44 2019/8/31 0031
     * @Param [admin]
     * @return com.swt.draw.vo.BaseResponse
     **/
    @PostMapping("/updatePwd")
    public BaseResponse updatePwd(Admin admin){
        BaseResponse response = new BaseResponse();
        AdminExample example = new AdminExample();
        AdminExample.Criteria criteria = example.createCriteria();
        criteria.andAdminNoEqualTo(admin.getAdminNo());
        admin.setAdminPwd(new Md5Hash(admin.getAdminPwd(), admin.getAdminLoginName(), 2).toString());
        adminMapper.updateByExampleSelective(admin, example);
        response.setCode(1001);
        response.setDesc("success");
        return response;
    }

    /**
     * @Author ZPF
     * @Description 用户修改自身密码
     * @Date 15:24 2019/9/1 0001
     * @Param [pwdData]
     * @return com.swt.draw.vo.BaseResponse
     **/
    @PostMapping("/updateSelfPwd")
    public BaseResponse updateSelfPwd(@RequestBody JSONObject pwdData){
        BaseResponse response = new BaseResponse();
        if(pwdData == null || !pwdData.containsKey("oldPwd") || !pwdData.containsKey("newPwd")){
            return response;
        }
        // 校验密码是否匹配
        Admin admin = (Admin) SecurityUtils.getSubject().getPrincipal();
        String oldPwd = pwdData.getString("oldPwd");
        if(admin.getAdminPwd().equals(new Md5Hash(oldPwd, admin.getAdminLoginName(), 2).toString())){
            Admin updateAdmin = new Admin();
            String newPwd = pwdData.getString("newPwd");
            updateAdmin.setAdminPwd(new Md5Hash(newPwd, admin.getAdminLoginName(), 2).toString());
            updateAdmin.setAdminNo(admin.getAdminNo());
            AdminExample example = new AdminExample();
            AdminExample.Criteria criteria = example.createCriteria();
            criteria.andAdminNoEqualTo(admin.getAdminNo());
            adminMapper.updateByExampleSelective(updateAdmin,example);
            response.setCode(1001);
            response.setDesc("success");
        }else {
            response.setDesc("密码不正确");
            return response;
        }
        return response;
    }
}
